﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using System.Data;
using System.Windows.Forms;

namespace FixEd.Parsers
{
        internal static class ParserManager
        {
            internal static Dictionary<Guid, IParser> AvailableParsers = new Dictionary<Guid, IParser>();

            internal static void LoadParsers()
            {
                string root = Path.GetDirectoryName(Directory.GetCurrentDirectory());

                foreach (string file in Directory.GetFiles(root.Replace("bin", "") + Properties.Settings.Default.ParserDirectory, "*.dll"))
                {
                    Assembly potentialParser = Assembly.LoadFile(file);
                    Type[] types = potentialParser.GetExportedTypes();
                    VerifiyImplements(potentialParser, types);
                }

            }

            private static void VerifiyImplements(Assembly potentialParser, Type[] types)
            {
                foreach (Type item in types)
                {
                    /* Make sure the assembly implements IParser **/
                    if (item.GetInterface("FixEd.Parsers.IParser") == null) continue;

                    /* get the parsers internal classname */
                    Type parserType = potentialParser.GetType(item.ToString());

                    /* instantiate it */
                    object parser = potentialParser.CreateInstance(parserType.FullName);

                    /* add it to the list */
                    if (parser == null) continue;
                    AvailableParsers.Add(((IParser)parser).ID, (IParser)parser);
                }
            }

            internal static DataSet OnParseFile(Guid callingParser)
            {
                foreach (Guid item in AvailableParsers.Keys)
                {
                    if (item.CompareTo(callingParser) == 0)
                    {
                        return AvailableParsers[item].ParseFile();
                    }
                }
                return null;
            }

            internal static void OnSaveFile(Guid callingParser, DataSet ds, string filePath)
            {
                foreach (Guid item in AvailableParsers.Keys)
                {
                    if (item.CompareTo(callingParser) == 0)
                    {
                        AvailableParsers[item].Save(ds, filePath);
                    }
                }
            }
        }
}
